export default {
    props: {
        headerImg: {
            type: String,
            default: ''
        },
        title: {
            type: String,
            default: ''
        },
        subTitle: {
            type: String,
            default: ''
        },
        bottomText: {
            type: String,
            default: '长按识别小程序码'
        },
        styleDiy: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            canvasW: 0,
            canvasH: 0,
            ctx: null,
            isShow: false,
            qrcode: '',
            isDone: false
        };
    },
    methods: {
        //显示
        showCanvas(qrcode) {
            this.isShow = true;
            this.qrcode = qrcode;
            this.__init();
        },
        //初始化画布
        async __init() {
            this.isDone = false;
            uni.$emit('showLoad',{text:'正在生成，若缩略图过大可能耗时较长，请耐心等待...'});
            this.ctx = uni.createCanvasContext('my-canvas', this);
            this.canvasW = uni.upx2px(550);
            this.canvasH = uni.upx2px(780);
            //设置画布背景透明
            this.ctx.setFillStyle('rgba(255, 255, 255, 0)');
            //设置画布大小
            this.ctx.fillRect(0, 0, this.canvasW, this.canvasH);
            //绘制圆角背景
            this.drawRoundRect(this.ctx, 0, 0, this.canvasW, this.canvasH, uni.upx2px(18),
                'rgba(255, 255, 255, 1)');
            //获取标题图片
            let headerImg = await this.getImageInfo(this.headerImg);
            let hW = uni.upx2px(500);
            let hH = uni.upx2px(320);

            //绘制标题图
            this.drawRoundImg(
                this.ctx,
                headerImg.path,
                hW / 4 + uni.upx2px(20),
                (this.canvasW - hW) / 2,
                hW / 2,
                hH,
                uni.upx2px(16)
            );
            //绘制标题
            this.ctx.setFontSize(18); //设置标题字体大小
            this.ctx.setFillStyle('#333'); //设置标题文本颜色
            let tWidth = this.ctx.measureText(this.title).width;
            if (tWidth > hW) {
                this.ctx.fillText(
                    this.title.length >= 12 ? this.title.slice(0, 12) + '...' : this.title,
                    (this.canvasW - hW) / 2,
                    (this.canvasW - hW) / 2 + hH + uni.upx2px(60)
                );
            } else {
                this.ctx.fillText(this.title, (this.canvasW - hW) / 2, (this.canvasW - hW) / 2 + hH + uni.upx2px(
                    60));
            }

            //绘制副标题（长度处理，一行17字，最多3行）
            this.ctx.setFontSize(14);
            this.ctx.setFillStyle('#858585');
            let sWidth = this.ctx.measureText(this.subTitle).width;
            if (sWidth > hW) {
                var text = [];
                for (let i = 0; i <= this.subTitle.length / 17; i++) {
                    if (text.length <= 0) {
                        text[i] = this.subTitle.slice(i, 17);
                    } else {
                        text[i] = this.subTitle.slice(this.subTitle.indexOf(text[i - 1]) + 17, 17 * (i + 1));
                    }
                }
                if (text.length > 3) {
                    for (let i = 0; i < 3; i++) {
                        this.ctx.fillText(
                            i == 2 ? text[i] + '...' : text[i],
                            (this.canvasW - hW) / 2,
                            (this.canvasW - hW) / 2 + i * 20 + hH + uni.upx2px(110)
                        );
                    }
                } else {
                    for (let i = 0; i < text.length; i++) {
                        this.ctx.fillText(
                            text[i],
                            (this.canvasW - hW) / 2,
                            (this.canvasW - hW) / 2 + i * 20 + hH + uni.upx2px(110)
                        );
                    }
                }
            } else {
                this.ctx.fillText(this.subTitle, (this.canvasW - hW) / 2, (this.canvasW - hW) / 2 + hH + uni.upx2px(
                    110));
            }
            //绘制虚线
            this.drawDashLine(
                this.ctx,
                (this.canvasW - hW) / 2 + uni.upx2px(20),
                (this.canvasW - hW) / 2 + hH + uni.upx2px(240),
                this.canvasW - (this.canvasW - hW) / 2 - uni.upx2px(20),
                (this.canvasW - hW) / 2 + hH + uni.upx2px(240),
                5
            );
            //左边实心圆
            this.drawEmptyRound(this.ctx, 0, (this.canvasW - hW) / 2 + hH + uni.upx2px(240), uni.upx2px(20));
            //右边实心圆
            this.drawEmptyRound(this.ctx, this.canvasW, (this.canvasW - hW) / 2 + hH + uni.upx2px(240), uni.upx2px(
                20));
            //提示文案
            this.ctx.setFontSize(12);
            this.ctx.setFillStyle('#858585');
            this.ctx.fillText(
                this.bottomText,
                (this.canvasW - hW) / 2 + uni.upx2px(34),
                (this.canvasW - hW) / 2 + hH + uni.upx2px(300)
            );
            //介绍文案
            this.ctx.setFontSize(12);
            this.ctx.setFillStyle('#858585');
            this.ctx.fillText(
                this.bottomText,
                (this.canvasW - hW) / 2 + uni.upx2px(34),
                (this.canvasW - hW) / 2 + hH + uni.upx2px(300)
            );
            //小程序码
            let qrcodeImg = await this.getImageInfo(this.qrcode);
            this.ctx.drawImage(
                qrcodeImg.path,
                uni.upx2px(384),
                (this.canvasW - hW) / 2 + hH + uni.upx2px(264),
                uni.upx2px(156),
                uni.upx2px(156)
            );

            //延迟渲染
            setTimeout(() => {
                this.ctx.draw(true, () => {
                    this.isDone = true;
                    uni.$emit('closeLoad');
                });
            }, 500);
        },
        // 扣边框圆
        drawEmptyRound(ctx, x, y, radius) {
            ctx.save();
            ctx.beginPath();
            // ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
            // ctx.setFillStyle('rgba(117, 117, 117, .6)');
            // ctx.fill();
            if (x > 0) {
                ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
                ctx.clip();
                ctx.clearRect(x - radius, y - radius, 2 * radius, 2 * radius);
            } else {
                ctx.arc(x, y, radius, 0, 2 * Math.PI);
                ctx.clip();
                ctx.clearRect(x, y - radius, radius, 2 * radius);
            }
            ctx.restore();
            ctx.closePath();
        },
        //绘制虚线
        drawDashLine(ctx, x1, y1, x2, y2, dashLength) {
            ctx.setStrokeStyle('#cccccc'); //设置线条的颜色
            ctx.setLineWidth(1); //设置线条宽度
            var dashLen = dashLength,
                xpos = x2 - x1, //得到横向的宽度;
                ypos = y2 - y1, //得到纵向的高度;
                numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen);
            //利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
            for (var i = 0; i < numDashes; i++) {
                if (i % 2 === 0) {
                    ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
                    //有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
                } else {
                    ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
                }
            }
            ctx.stroke();
        },
        //带圆角图片
        drawRoundImg(ctx, img, x, y, width, height, radius) {
            ctx.beginPath();
            ctx.save();
            // 左上角
            ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5);
            // 右上角
            ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2);
            // 右下角
            ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5);
            // 左下角
            ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI);
            ctx.setStrokeStyle('#FFFFFF');
            ctx.stroke();
            ctx.clip();
            ctx.drawImage(img, x, y, width, height);
            ctx.restore();
            ctx.closePath();
        },
        //圆角矩形
        drawRoundRect(ctx, x, y, width, height, radius, color) {
            ctx.save();
            ctx.beginPath();
            ctx.setFillStyle(color);
            ctx.setStrokeStyle(color);
            ctx.setLineJoin('round'); //交点设置成圆角
            ctx.setLineWidth(radius);
            ctx.strokeRect(x + radius / 2, y + radius / 2, width - radius, height - radius);
            ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2);
            ctx.stroke();
            ctx.closePath();
        },
        //获取图片
        getImageInfo(imgSrc) {
            let _this = this;
            if (_this.$isAppPlus) {
                return new Promise((resolve, reject) => {
                    uni.getImageInfo({
                        src: imgSrc,
                        success: image => {
                            resolve(image);
                            console.log('获取图片成功', image);
                        },
                        fail: err => {
                            reject(err);
                            console.log('获取图片失败', err);
                        }
                    });
                });
            }
            if (_this.$isMp) {
                return new Promise((resolve, reject) => {
                    _this.$http
                        .post('/attachment/attachment/getImgInfo', {
                            img: encodeURIComponent(imgSrc),
                            encryptedData: 1,
                        })
                        .then(res => {
                            let filePath = wx.env.USER_DATA_PATH + '/' + _this.$func.randomString(10) + res.data.type;
                            let fileManager = uni.getFileSystemManager();
                            fileManager.writeFile({
                                filePath: filePath, // 指定图片的临时路径
                                data: res.data.data, // 要写入的文本或二进制数据
                                encoding: 'base64', // 指定写入文件的字符编码
                                success: res => {
                                    uni.getImageInfo({
                                        src: filePath,
                                        success: image => {
                                            resolve(image);
                                        },
                                        fail: err => {
                                            _this.isShow = false;
                                            uni.$emit('closeLoad');
                                            uni.showModal({
                                                title: '提示',
                                                content: '生成海报失败，请联系客服',
                                                showCancel: false
                                            })
                                            reject(err);
                                        }
                                    });
                                },
                                file: err => {
                                    _this.isShow = false;
                                    uni.$emit('closeLoad');
                                    uni.showModal({
                                        title: '提示',
                                        content: '生成海报失败，请联系客服',
                                        showCancel: false
                                    })
                                }
                            })
                        })
                        .catch(res => {
                            _this.isShow = false;
                            uni.$emit('closeLoad');
                            uni.showModal({
                                title: '提示',
                                content: '生成海报失败，请联系客服',
                                showCancel: false
                            })
                        });
                });
            }
        },
        //保存图片到相册
        saveImage() {
            let _this = this;
            if (_this.$isMp) {
                //判断用户授权
                uni.getSetting({
                    success(res) {
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            uni.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success() {
                                    //这里是用户同意授权后的回调
                                    _this.savePoster();
                                },
                                fail() {
                                    //这里是用户拒绝授权后的回调
                                    uni.showToast({
                                        title: '请在小程序设置里打开相册读写权限',
                                        icon: 'none'
                                    });
                                }
                            });
                        } else {
                            //用户已经授权过了
                            _this.savePoster();
                        }
                    }
                });
            }
            if (_this.$isAppPlus) {
                _this.savePoster();
            }
        },
        savePoster() {
            var that = this;
            uni.showLoading({
                title: '保存中',
                mask: true
            })
            uni.canvasToTempFilePath({
                    canvasId: 'my-canvas',
                    quality: 1,
                    complete: res => {
                        uni.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success(res) {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '已保存到相册',
                                    icon: 'success',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    that.isShow = false;
                                }, 2000);
                            }
                        });
                    }
                },
                this
            );
        }
    }
};
